<template>
  <div>
    <el-dialog
      v-model="visible"
      :title="$t('user.selectCoupons')"
      width="50%"
      class="components-update-user-coupon"
      @close="onCloseDialog"
    >
      <el-form
        :inline="true"
        :model="searchForm"
        class="demo-form-inline form"
        @submit.prevent
      >
        <el-form-item>
          <el-input
            v-model="couponName"
            :placeholder="$t('user.couponTip1')"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <div
            class="default-btn primary-btn"
            @click="onSearch"
          >
            {{ $t('user.query') }}
          </div>
        </el-form-item>
      </el-form>
      <div class="prods-select-body">
        <el-table
          v-loading="dataListLoading"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          :data="dataList"
          style="width: 100%"
          @selection-change="onSelectChange"
        >
          <el-table-column
            v-if="isSingle"
            width="50"
            header-align="center"
            align="center"
          >
            <template #default="scope">
              <div>
                <el-radio
                  v-model="singleSelectCouponId"
                  :label="scope.row.couponId"
                  @change="onGetSelectProdRow(scope.row)"
                >
&nbsp;
                </el-radio>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="!isSingle"
            type="selection"
            header-align="center"
            align="center"
            width="50"
          />
          <el-table-column
            prop="couponName"
            header-align="center"
            align="center"
            :label="$t('marketing.couponName')"
          />
          <el-table-column
            prop="getWay"
            header-align="center"
            align="center"
            :label="$t('coupon.couponType')"
          />
          <el-table-column
            prop="stocks"
            header-align="center"
            align="center"
            :label="$t('user.stockNum')"
          />
          <el-table-column
            prop="limitNum"
            header-align="center"
            align="center"
            :label="$t('user.couponUpperLimit')"
          />
          <el-table-column
            header-align="center"
            align="center"
            :label="$t('user.perRecevies')"
            width="200"
          >
            <template #header>
              <span>{{ $t('user.perRecevies') }}</span>
              <el-tooltip
                placement="top"
                effect="light"
              >
                <el-icon class="QuestionFilled">
                  <QuestionFilled />
                </el-icon>
                <template #content>
                  <div>
                    {{ $t('user.couponTip2') }}
                  </div>
                </template>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-input-number
                v-model="scope.row.eachObtain"

                controls-position="right"
                :min="scope.row.stocks > 0 ? 1 : 0"
                :max="
                  scope.row.stocks > 0
                    ? scope.row.stocks >= scope.row.limitNum
                      ? scope.row.limitNum
                      : scope.row.stocks
                    : 0
                "
                @blur="onChangeEachObtain(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="dataList.length"
          :current-page="page.pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @update:page-size="onPageSizeChange"
          @update:current-page="onPageChange"
        />
      </div>
      <template #footer>
        <div>
          <div
            class="default-btn"
            @click="visible = false"
          >
            {{ $t('remindPop.cancel') }}
          </div>
          <div
            class="default-btn primary-btn"
            :loading="confirmLoad"
            @click="onSubmit()"
          >
            {{ $t('remindPop.confirm') }}
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshSelectCouponList', 'refreshDataList'])

const props = defineProps({
  value: {
    default: '',
    type: String
  },
  // 获取方式 null:默认（客户领取+平台发放） 0=客户领取 1=平台发放
  getWay: {
    default: null,
    type: Number
  },
  isSingle: {
    default: false,
    type: Boolean
  },
  // 最大上传数量
  limit: {
    default: 9,
    type: Number
  }
})
const visible = ref(false)
const dataForm = ref({
  userIds: [],
  coupons: []
})
const init = ids => {
  visible.value = true
  dataForm.value.userIds = ids
  onGetDataList()
}
// 每页数
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const onPageSizeChange = val => {
  page.value.pageSize = val
  page.value.currentPage = 1
  onGetDataList(page.value)
}
// 当前页
const onPageChange = val => {
  page.value.currentPage = val
  onGetDataList(page.value)
}
// 分页获取标签
const dataListLoading = ref(false)
const dataList = ref([{
  limitNum: 0,
  stocks: 0,
  getWay: 0,
  subTitle: '',
  couponName: ''
}]) // 标签
const searchForm = ref({})

const onGetDataList = pageParam => {
  dataListLoading.value = true
  http({
    url: http.adornUrl('/admin/coupon/list'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.value.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.value.pageSize : pageParam.pageSize,
          getWay: props.getWay
        },
        searchForm.value
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    dataList.value.forEach(item => {
      // 平台投放 / 用户领取
      item.getWay = item.getWay === 1 ? $t('coupon.platformDistribution') : $t('coupon.userClaim')
      item.eachObtain = 1
    })
    page.value.total = data.total
    dataListLoading.value = false
  })
}
// 搜索
const couponName = ref(null)

const onSearch = () => {
  searchForm.value.couponName = couponName.value
  onGetDataList(page.value)
}
// 单选商品事件
const dataListSelections = ref([])
const onGetSelectProdRow = row => {
  dataListSelections.value = [row]
}
// 多选
// 多选点击事件
const onSelectChange = selection => {
  dataList.value.forEach(tableItem => {
    const selectedProdIndex = selection.findIndex(selectedCoupon => {
      if (!selectedCoupon) {
        dataListSelections.value = []
        return false
      }
      return selectedCoupon.couponId === tableItem.couponId
    })
    const dataSelectedProdIndex = dataListSelections.value.findIndex(
      dataSelectedCoupon => dataSelectedCoupon.couponId === tableItem.couponId
    )
    if (selectedProdIndex > -1 && dataSelectedProdIndex === -1) {
      dataListSelections.value.push(tableItem)
    } else if (selectedProdIndex === -1 && dataSelectedProdIndex > -1) {
      dataListSelections.value.splice(dataSelectedProdIndex, 1)
    }
  })
}
// 确定事件
const onSubmit = () => {
  // 商品单选的情况
  if (props.isSingle) {
    dataListSelections.value.length && emit('refreshSelectCouponList', dataListSelections.value[0])
    dataListSelections.value = []
    visible.value = false
    return
  }
  // 多选
  const coupons = []
  dataListSelections.value?.forEach(item => {
    const couponIndex = coupons.findIndex(coupon => coupon.couponId === item.couponId)
    if (couponIndex === -1) {
      coupons.push({
        couponId: item.couponId,
        couponName: item.couponName,
        subTitle: item.subTitle,
        limitNum: item.limitNum,
        eachObtain: item.eachObtain
      })
    }
  })

  dataForm.value.coupons = coupons
  dataListSelections.value = []
  onConfirm()
}
const onChangeEachObtain = (row) => {
  if (!row.eachObtain && row.eachObtain !== 0) {
    row.eachObtain = row.stocks > 0 ? 1 : 0
  }
}
const confirmLoad = ref(false)
const onConfirm = () => {
  if (!dataForm.value.userIds) {
    return
  }
  if (!dataForm.value.coupons || !dataForm.value.coupons.length) {
    return ElMessage.error($t('user.pleaseSelectCoupons'))
  }
  confirmLoad.value = true
  const coupons = []
  dataForm.value.coupons.forEach(element => {
    const obj = {}
    obj.couponId = element.couponId
    obj.nums = element.eachObtain
    coupons.push(obj)
  })
  dataForm.value.coupons = coupons
  const param = dataForm.value
  http({
    url: http.adornUrl('/admin/coupon/sendUserCoupon'),
    method: 'put',
    data: http.adornData(param)
  })
    .then(() => {
      ElMessage({
        message: $t('remindPop.success'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          visible.value = false
          confirmLoad.value = false
          emit('refreshDataList', page.value)
        }
      })
    })
    .catch(() => {})
}

const onCloseDialog = () => {
  couponName.value = null
  searchForm.value = {}
  page.value = {
    total: 0, // 总页数
    currentPage: 1, // 当前页数
    pageSize: 10 // 每页显示多少条
  }
}
defineExpose({ init })
</script>
<style lang="scss" scoped>
.components-update-user-coupon {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
